﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TaxiCaosSOAPService.Dominio;
using System.Data.SqlClient;
using NHibernate;
using System.Globalization;

namespace TaxiCaosSOAPService.Persistencia
{
    public class FacturaDAO : BaseDAO<Factura, int>
    {
        public string ObtenerSiguienteNroSerie()
        {
            string serie = "";
            string sql = "select ISNULL(MAX(convert(INTEGER,f.NroSerie)),0)+1 as NroSerie from factura f";
            using (SqlConnection con = new SqlConnection(ConexionUtil.ObtenerConexion()))
            {
                con.Open();
                using (SqlCommand com = new SqlCommand(sql, con))
                {
                    using (SqlDataReader resultado = com.ExecuteReader())
                    {
                        if (resultado.Read())
                        {
                            serie = resultado["NroSerie"].ToString();
                        }

                    }

                }
            }

            return serie.PadLeft(10, '0');
        }


        public string ObtenerImportexReserva(string nroReserva)
        {
            try
            {
                using (ISession sesion = NHibernateHelper.ObtenerSesion())
                {
                    string sentenciaSQL = "select MontoNeto from Factura where IdReserva = :IdReserva";
                    IQuery query = sesion.CreateQuery(sentenciaSQL);
                    query.SetParameter("IdReserva", int.Parse(nroReserva));
                    IList<double> monto = query.List<double>();
                    return monto[0].ToString("0.00", CultureInfo.InvariantCulture);
                }
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        public bool ActualizarFacturaConPago(string nroReserva, int idPago)
        {
            try
            {
                using (ISession sesion = NHibernateHelper.ObtenerSesion())
                {
                    string sentenciaSQL = "update Factura set IdPago = :idPago where idReserva = :nroReserva";
                    IQuery query = sesion.CreateQuery(sentenciaSQL);
                    query.SetParameter("nroReserva", int.Parse(nroReserva));
                    query.SetParameter("idPago", idPago);
                    query.ExecuteUpdate();
                }

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

        }

    }
}